<?php

/**
 * this script handle upload file to file storage.
 */

require_once '../include/init.php';

defined('NUO_MEDIA_PATH') or define('NUO_MEDIA_PATH', NUO_ROOT_PATH . '/media');

define('STORAGE_SERVICE', 1);

define('STORAGE_HOST', 'http://namnv.younetco.com/nuo2/');

$log = Nuo::getHelper('@log') -> getWriter('upload');

if (!isset($_FILES['fileData']))
{
    throw new Exception("invalid file data");
}

$file = $_FILES['fileData'];

$uuid = Nuo::UUID('core@photo');

$file_name = $file['name'];

$uploaded_filename = $file['tmp_name'];

$file_size = $file['size'];

$file_ext = substr($file_name, strrpos($file_name, '.') + 1);

$width = $height = 0;

$mime_type = 'unknown';

$destination_sub_dir = date('Y/m/d');

if (!is_dir(NUO_MEDIA_PATH . '/' . $destination_sub_dir))
{
    $check_dir = NUO_MEDIA_PATH;

    foreach (explode('/', $destination_sub_dir) as $dir)
    {
        $check_dir .= '/' . $dir;

        if (!is_dir($check_dir) && !mkdir($check_dir, 0777, 1))
        {
            throw new Exception("invalid directory, $check_dir is not writeable.");
        }
    }
}

$destination_path = $destination_sub_dir . '/' . $uuid . '.' . $file_ext;

$destination_full_path = NUO_MEDIA_PATH . '/' . $destination_path;

list($width, $height) = getimagesize($uploaded_filename);

$mime_type = mime_content_type($uploaded_filename);

if (!move_uploaded_file($uploaded_filename, $destination_full_path))
{
    throw new Exception("can not move upload file from $uploaded_filename to $destination");
}

$data = array(
    'id' => $uuid,
    'path' => $destination_path,
    'url' => trim(STORAGE_HOST, '/') . '/' . trim($destination_path, '/'),
    'size' => $file_size,
    'width' => $width,
    'height' => $height,
    'title' => $file_name,
    'desc' => date("F j, Y, g:i a"),
    'service' => STORAGE_SERVICE,
    'creation_date' => date('Y-m-d H:i:s'),
    'mime_type' => $mime_type,
);

$table = Nuo::getTable('core@photo');

$table -> insert($data);

$log -> write(var_export($file, 1), $uuid, $file_ext, var_export($size, 1), var_export($mime_type, 1));
